package com.gf.pokemon.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.gf.pokemon.platform.exception.PokeErrorCode;
import com.gf.pokemon.platform.exception.PokeException;

public class PokeUtils {
	
	private static final Logger logger = Logger.getLogger(PokeUtils.class);
	
	private static SimpleDateFormat sim = new SimpleDateFormat("MM/dd/yyyy");
	
	public static Date parseDateStr(String date) throws PokeException{
		try {
			return sim.parse(date);
		} catch (ParseException e) {
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"时间格式错误");
		}
	}
	
	public static String parseDate(Date date) throws PokeException{
		return sim.format(date);
	}
	
	/**
	 * 构造用户Excel文件流
	 * @param sheetName
	 * @param headers
	 * @param datas
	 * @return
	 * @throws PokeException
	 */
	public static byte[] buildExcelData(String sheetName,List<String> headers,List<List<String>> datas) throws PokeException{
		if(headers==null || datas==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"headers 或   datas 为空");
		}
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		// 头标签
		HSSFRow row = sheet.createRow(0);
		for(int i=0;i<headers.size();i++){
			HSSFCell cell = row.createCell(i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(headers.get(i));
		}

		//数据
		for(int i=0;i<datas.size();i++){
			List<String> rowDatas = datas.get(i);
			HSSFRow dataRow = sheet.createRow(i+1);
			for(int j=0;j<rowDatas.size();j++){
				HSSFCell cell = dataRow.createCell(j);
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(rowDatas.get(j));
			}
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			wb.write(out);
			wb.close();
			return out.toByteArray();
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			throw new PokeException(PokeErrorCode.INVALID_PARAM,e.getMessage());
		}
	}
	
}
